<!-- param: viewMode-控制显示，id-控制数据加载，mode-控制button加载 -->
<template>
  <el-container
    v-loading="loading"
  >
    <!-- 右侧菜单 -->
    <el-container>
      <!-- 功能按钮组 -->
      <el-header height="42px">
        <span v-if="viewMode == 'list'" class="ik-list-title">
          <span class="svg-container ik-list-icon">
            <svg-icon icon-class="database"/>
          </span>
          <span>数据列表</span>
        </span>
        <!-- 列表页菜单 -->
        <el-button-group v-if="viewMode === 'list'" class="ik-list-menu">
          <el-button class="ik-list-menu-btn" size="medium" @click="listCreateBtn">新增</el-button>
          <el-button class="ik-list-menu-btn" size="medium" @click="listUpdateBtn">修改</el-button>
          <el-button class="ik-list-menu-btn" size="medium" @click="listDetailsBtn">详情</el-button>
          <el-button class="ik-list-menu-btn" size="medium" @click="listDeleteBtn">删除</el-button>
        </el-button-group>
        <!-- 信息页菜单 -->
        <el-button-group v-if="viewMode === 'info'" class="ik-list-menu">
          <!-- 编辑模式  add - 新增模式, edit - 编辑模式, details - 详情模式 -->
          <el-button
            v-if="mode == 'edit' || mode == 'details' "
            class="ik-list-menu-btn"
            size="medium"
            @click="infoCreateBtn"
          >新增
          </el-button>
          <el-button v-if="mode == 'details'" class="ik-list-menu-btn" size="medium" @click="infoUpdateBtn">修改
          </el-button>
          <el-button
            v-if="mode == 'edit' || mode == 'details'"
            class="ik-list-menu-btn"
            size="medium"
            @click="infoCopyBtn"
          >复制
          </el-button>
          <el-button v-if="mode == 'edit'" class="ik-list-menu-btn" size="medium" @click="infoDetailsBtn">详情
          </el-button>
          <el-button v-if="mode == 'add' || mode == 'edit'" class="ik-list-menu-btn" size="medium" @click="infoSaveBtn">
            保存
          </el-button>
          <el-button class="ik-list-menu-btn" size="medium" @click="infoCancelBtn">取消</el-button>
        </el-button-group>
      </el-header>
      <el-main>
        <!-- 表头 -->
        <el-form
          v-if="viewMode == 'info'"
          id="ik-info-head"
          v-model="data.head"
          class="ik-info-head"
          :inline="true"
          label-width="120px"
          :disabled="mode == 'details'"
        >
          <el-row>
            <!-- 文本 -->
            <el-col :span="6">
              <ik-form-text
                :ref="'input_code'"
                v-model="data.head['code']"
                code="code"
                name="编码"
                default-value=""
                :min-length="0"
                :max-length="20"
                :disabled="false"
                :require="true"
                @onFieldChange="onFieldChange"
              />
            </el-col>
            <!-- 文本 -->
            <el-col :span="6">
              <ik-form-text
                :ref="'input_name'"
                v-model="data.head['name']"
                code="name"
                name="名称"
                default-value=""
                :min-length="0"
                :max-length="20"
                :disabled="false"
                :require="true"
                @onFieldChange="onFieldChange"
              />
            </el-col>
          </el-row>
        </el-form>
        <!-- 表身 -->
        <el-tabs
          v-if="viewMode === 'info'"
          ref="ik-info-body"
          v-model="activeTab"
          class="data-directory-tabs-info"
          type="card"
        >
          <el-tab-pane
            :key="bodyMap[0].key"
            :name="bodyMap[0].key"
            :label="bodyMap[0].name"
            style="height:100%;"
          >
            <el-table
              ref="tablesub"
              v-loading="loading"
              v-horizontal-scroll="'always'"
              :data="data.body[bodyMap[0].key]"
              element-loading-text="加载中..."
              :stripe="true"
              :border="true"
              :fit="true"
              class="ik-list-table"
              height="100%"
              :header-row-class-name="'ik-list-table-header-row'"
              :header-cell-class-name="'ik-list-table-header-cell'"
              :row-class-name="'ik-list-table-body-row'"
              :cell-class-name="'ik-list-table-body-cell'"
              :highlight-current-row="true"
            >
              <!-- 操作区 -->
              <el-table-column
                v-if="mode !== 'details'"
                prop="pluss"
                label="操作"
                width="180"
              >
                <template v-slot:header>
                  <div class="button-action">
                    <span style="padding:0px 12px;">操作</span>
                    <el-button
                      circle
                      :style="{width:'26px',height:'26px',color:'#409EFF',padding:'3px 0','margin-top':'3px'}"
                      title="添加首行"
                      @click="addRow(activeTab, -1)"
                    >+
                    </el-button>
                  </div>
                </template>
                <template slot-scope="scope">
                  <div class="button-action">
                    <el-button
                      circle
                      :style="{width:'28px',height:'28px',color:'#409EFF',padding:'3px 0','margin-top':'3px'}"
                      @click.stop="addRow(bodyMap[0].key, scope.$index)"
                    >+
                    </el-button>
                    <el-button
                      circle
                      :style="{width:'28px',height:'28px',color:'#409EFF',padding:'3px 0','margin-top':'3px'}"
                      @click.stop="delRow(bodyMap[0].key, scope.$index)"
                    >-
                    </el-button>
                  </div>
                </template>
              </el-table-column>
              <ik-column-text
                code="code"
                name="编码"
                :require="true"
                :edit="mode !== 'details'"
                @onFieldChange="onBodyFieldChange"
              />
              <ik-column-text
                code="name"
                name="名称"
                :require="true"
                :edit="mode !== 'details'"
                @onFieldChange="onBodyFieldChange"
              />
              <ik-column-text
                code="dicDescribe"
                name="词典描述"
                :edit="mode !== 'details'"
                @onFieldChange="onBodyFieldChange"
              />
              <ik-column-number
                code="ind"
                name="序号"
                :precision="0"
                :rules="[{ code: 'positiveNumber', message: '需为正数'}]"
                :edit="mode !== 'details'"
                @onFieldChange="onBodyFieldChange"
              />
              <ik-column-text
                code="pinyinCode"
                name="拼音码"
                :edit="mode !== 'details'"
                @onFieldChange="onBodyFieldChange"
              />
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <!-- 查询区 -->
        <div class="querybg">
          <el-collapse
            v-if="viewMode === 'list'"
            v-model="searcherActive"
            class="ik-list-searcher"
            accordion
          >
            <el-collapse-item class="ik-list-searcher-item" title="" name="1">
              <!-- 标题栏 -->
              <template slot="title">
                <div class="ik-list-searcher-item-titles">
                  <span class="svg-container ik-list-icon">
                    <svg-icon icon-class="search"/>
                  </span>
                  查询条件
                </div>
              </template>
              <!-- 查询菜单 -->
              <el-form
                id="ik-info-head"
                v-model="searcher"
                class="ik-info-head"
                :inline="true"
                label-width="120px"
                :disabled="false"
              >
                <el-row>
                  <!-- 文本 -->
                  <el-col :span="6">
                    <ik-form-text
                      :ref="'input_code'"
                      v-model="searcher['code']"
                      code="code"
                      name="编码"
                      default-value=""
                      :min-length="0"
                      :max-length="20"
                      :disabled="false"
                      :require="false"
                    />
                  </el-col>
                  <!-- 文本 -->
                  <el-col :span="6">
                    <ik-form-text
                      :ref="'input_name'"
                      v-model="searcher['name']"
                      code="name"
                      name="名称"
                      default-value=""
                      :min-length="0"
                      :max-length="20"
                      :disabled="false"
                      :require="false"
                      @onFieldChange="onFieldChange"
                    />
                  </el-col>
                </el-row>
              </el-form>
              <!-- 操作按钮 -->
              <div class="query-class">
                <div class="query-btn-warp">
                  <el-button type="primary" size="small" @click="searchBtn">查询</el-button>
                  <el-button type="primary" size="small" @click="resetBtn">重置</el-button>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <!-- 数据表 -->
        <el-table
          v-if="viewMode === 'list'"
          ref="table"
          v-loading="listLoading"
          :data="tableData"
          element-loading-text="加载中..."
          :stripe="true"
          :border="true"
          :fit="true"
          class="ik-list-table"
          height="calc(100% - 50px)"
          :header-row-class-name="'ik-list-table-header-row'"
          :header-cell-class-name="'ik-list-table-header-cell'"
          :row-class-name="'ik-list-table-body-row'"
          :cell-class-name="'ik-list-table-body-cell'"
          :highlight-current-row="true"
          @row-click="rowClick"
        >
          <ik-column-text
            code="code"
            name="编码"
            :edit="false"
          />
          <ik-column-text
            code="name"
            name="名称"
            :edit="false"
          />
        </el-table>
      </el-main>
      <!-- 分页组件 -->
      <el-footer height="40px">
        <ik-pagination
          ref="ik_list_pagination"
          :page-no="pagination.pageNo"
          :page-size="pagination.pageSize"
          :total-count="pagination.totalCount"
          @pageChangeMethod="pageChange"
        />
      </el-footer>
    </el-container>
  </el-container>
</template>
<script>
// 表单组件
import IkFormText from '@/components/ik/form/input/IkFormText'
import IkColumnText from '@/components/ik/table/ikColumn/IkColumnText'
import IkColumnNumber from '@/components/ik/table/ikColumn/IkColumnNumber'
import IkPagination from '@/components/ik/pagination/IkPagination'

import { getById, findPage, save, update, remove } from '@/api/ik/data/dataApi'

export default {
  components: {
    // 表单组件
    IkFormText,
    IkColumnText,
    IkColumnNumber,
    IkPagination
  },
  props: {},
  data() {
    return {
      // ===== ===== ===== ===== 全局属性 ===== ===== ===== =====
      // 后台接口路径
      bgPath: 'base/dictionary/diagdic/chdiagdirectory',
      // Web路径
      webPath: 'base/dictionary/diag_dic/ChDiagDirectory',
      // 标识字段JSON
      jsonStr: {
        robotTypes: '[{"key": "1", "value": "桌面机器人"}, {"key": "2", "value": "机器人"}, {"key": "3", "value": "平台"}]'
      },
      // 界面模式  info - 信息页, list - 列表页
      viewMode: '',
      // 编辑模式  add - 新增模式, edit - 编辑模式, details - 详情模式, list - 列表模式
      mode: '',
      // 加载标识、列表加载标识
      loading: false,
      listLoading: false,
      // ===== ===== ===== ===== 列表页属性 ===== ===== ===== =====
      // 查询器是否激活
      searcherActive: "0",
      searcher: {},
      // 列表页数据
      tableData: [],
      // 当前选中行
      activeRow: {},
      // 分页器
      pagination: {
        pageNo: 1,
        pageSize: 20,
        totalCount: 2
      },
      // ===== ===== ===== ===== 信息页属性 ===== ===== ===== =====
      // 当前数据id
      id: 0,
      // 当前数据
      data: {
        head: { 'id': 0, 'code': '', 'name': '' },
        body: { 'chDiagDictionary': [] }
      },
      // 子表清单
      bodyMap: [{ key: 'chDiagDictionary', name: '中医病词典项' }],
      // 当前子表
      activeTab: 'chDiagDictionary',
      verify: {
        head: {},
        body: {}
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    // 获取视图模式
    this.viewMode = this.$route.params.viewMode || "list"
    this.mode = this.$route.params.mode || "list"
    this.id = this.$route.query.id || 0
    // 初始化界面，设置模式取值
    if (this.mode === "list") {
      this.viewMode = "list"
    } else {
      this.viewMode = "info"
    }
    // 列表页进入时的处理
    if (this.viewMode === "list") {
      this.find()
    } else if (this.viewMode === "info") {
      if (this.id !== 0) {
        this.get(this.id)
      }
    }
  },
  methods: {
    // ===== ===== ===== ===== 工具方法 ===== ===== ===== =====
    // 工具方法 - 转为json
    toJson(jsonStr) {
      return JSON.parse(jsonStr)
    },
    // ===== ===== ===== ===== 工具栏按钮 ===== ===== ===== =====
    listCreateBtn() {
      this.$router.push({ path: '/business/manager/' + this.webPath + '/info/add' })
    },
    // 列表页编辑按钮点击
    listUpdateBtn() {
      // 是否选择行
      const $this = this
      if ($this.activeRow.id === undefined) {
        $this.$message({
          type: 'warning',
          message: '请选择需要编辑的行!'
        })
      } else {
        this.$router.push({
          path: '/business/manager/' + this.webPath + '/info/edit',
          query: { id: $this.activeRow.id }
        })
      }
    },
    // 列表页详情按钮点击
    listDetailsBtn() {
      // 是否选择行
      const $this = this
      if ($this.activeRow.id === undefined) {
        $this.$message({
          type: 'warning',
          message: '请选择需要编辑的行!'
        })
      } else {
        // 修改为详情模式
        this.$router.push({
          path: '/business/manager/' + this.webPath + '/info/details',
          query: { id: $this.activeRow.id }
        })
      }
    },
    // 列表页删除按钮点击
    listDeleteBtn() {
      // 是否选择行
      const $this = this
      if ($this.activeRow.id === undefined) {
        $this.$message({
          type: 'warning',
          message: '请选择需要删除的行!'
        })
      } else {
        // 问询是否删除
        this.$confirm('删除ID为' + $this.activeRow.id + '的数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delete($this.activeRow.id)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    // 信息页创建按钮点击
    infoCreateBtn() {
      this.$router.push({ path: '/business/manager/' + this.webPath + '/info/add' })
    },
    // 信息页编辑按钮点击
    infoUpdateBtn() {
      // 修改为编辑模式
      this.mode = "edit"
    },
    // 复制按钮点击事件
    infoCopyBtn() {
      // 修改id为控制
      this.data.head.id = 0
      // 修改为编辑模式
      this.mode = "edit"
    },
    infoDetailsBtn() {
      // 修改为编辑模式
      this.mode = "details"
      this.get(this.data.head.id)
    },
    // 保存按钮点击事件
    infoSaveBtn() {
      this.saveOrUpdate()
    },
    // 取消按钮点击事件
    infoCancelBtn() {
      // 修改为详情模式
      this.$router.push({ path: '/business/manager/' + this.webPath + '/list/list' })
    },
    // 查询
    searchBtn() {
      this.find()
    },
    // 重置
    resetBtn() {
      this.searcher = {}
      this.find()
    },
    // ===== ===== ===== ===== 信息页表格行维护 ===== ===== ===== =====
    //
    /**
     * 新增行按钮
     * @param curr
     * @param index
     */
    addRow(curr, index) {
      if (this.data.body[curr]) {
        if (this.data.body[curr].length > 0) {
          this.data.body[curr].splice(index + 1, 0, {})
        } else {
          this.data.body[curr].push({})
        }
      } else {
        this.data.body[curr] = []
        this.data.body[curr].push({})
      }
    },
    // 删除行按钮
    delRow(currt, index) {
      this.data.body[currt].splice(index, 1)
      for (const item in this.verify.body) {
        console.log(item)
        if (item.startsWith('item1' + '-' + index + '-')) {
          delete this.verify.body[item]
        }
      }
    },
    // ===== ===== ===== ===== 列表页表格点击 ===== ===== ===== =====
    // 行点击事件
    rowClick(row, column, event) {
      this.activeRow = row
    },
    // 字段变更事件
    onFieldChange(fieldName, oldValue, newValue, errorSign, errorMessage) {
      // 处理格式验证
      this.$set(this.data.head, fieldName, newValue)
      this.verify.head['head' + '-' + fieldName] = errorSign
      this.$emit('onFieldChange', fieldName, oldValue, newValue)
    },
    // 子表字段变更事件
    onBodyFieldChange(line, fieldName, oldValue, newValue, errorSign, errorMessage) {
      // 处理格式验证
      this.verify.body['item1' + '-' + line + '-' + fieldName] = errorSign
      this.$emit('onFieldChange', line, fieldName, oldValue, newValue)
    },
    // 分页器数据变更
    pageChange(pageNo, pageSize) {
      // 修改分页数据
      this.pagination.pageNo = pageNo
      this.pagination.pageSize = pageSize
      // 刷新数据
      this.find()
    },
    // ===== ===== ===== ===== 接口通讯方法 ===== ===== ===== =====
    // 保存或修改数据
    saveOrUpdate() {
      const $this = this
      // 验证
      for (const headInd in this.verify.head) {
        if (this.verify.head[headInd]) {
          $this.$message({ type: 'error', message: '数据格式异常' })
          console.log(this.verify)
          return
        }
      }
      for (const bodyInd in this.verify.body) {
        if (this.verify.body[bodyInd]) {
          console.log(this.verify.body[bodyInd])
          $this.$message({ type: 'error', message: '数据格式异常' })
          console.log(this.verify)
          return
        }
      }
      if ($this.data.head.id) {
        update($this.bgPath, $this.data).then(response => {
          // 设置ID
          $this.id = response.data
          // 刷新数据
          $this.get(response.data)
          $this.$message({
            type: 'success',
            message: '数据已保存!'
          })
          $this.viewMode = "info"
          $this.mode = "details"
        })
      } else {
        save($this.bgPath, $this.data).then(response => {
          // 设置ID
          $this.id = response.data
          // 刷新数据
          $this.get(response.data)
          $this.$message({
            type: 'success',
            message: '数据已保存!'
          })
          $this.viewMode = "info"
          $this.mode = "details"
        })
      }
    },
    // 删除数据
    delete(id) {
      const $this = this
      remove($this.bgPath, id).then(response => {
        $this.$message({
          type: 'warning',
          message: '数据已删除!'
        })
        $this.find()
      })
    },
    // 获取数据
    get(id) {
      const $this = this
      // 获取树组件数据
      this.loading = true
      getById($this.bgPath, id).then(response => {
        $this.data = response.data
      })
        .finally(() => {
          this.loading = false
        })
    },
    // 查询数据
    find() {
      const $this = this
      $this.listLoading = true
      // 获取树组件数据
      findPage($this.bgPath, $this.searcher, $this.pagination.pageSize, $this.pagination.pageNo).then(response => {
        // 设置表格数据
        $this.tableData = response.data.list
        // 设置分页器
        $this.pagination.totalCount = response.data.totalCount
        // 设置加载完成
        $this.listLoading = false
      }).catch(() => {
        $this.listLoading = false
      })
    }
  }
}
</script>
<style lang="scss">
@import "~@/styles/listinfo.scss";

.data-directory-tabs-info {
  height: calc(100% - 60px);
}

.data-directory-tabs-info .el-tabs__content {
  height: calc(100% - 53px);
  overflow: auto;
  min-height: 350px;
}
</style>
